package com.study.spring_ai_mcp_server.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.spring_ai_mcp_server.tool.WeatherService;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.support.ToolCallbacks;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.method.MethodToolCallback;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dejavu
 * @since 2025/7/22
 */
@Configuration
public class McpServerConfig {


    //声明工具
    @Bean
    public List<ToolCallback> mcpServerTools(WeatherService weatherService) {
        return List.of(ToolCallbacks.from(weatherService));
    }

    //声明资源
    //静态资源
    @Bean
    public List<McpServerFeatures.AsyncResourceSpecification> staticResources() {
        // 1. 创建资源定义
        McpSchema.Resource resource = new McpSchema.Resource(
                "system-info",
                "系统信息",
                "服务器运行时信息",
                "application/json",
                new McpSchema.Annotations(List.of(McpSchema.Role.ASSISTANT), 1.0)
        );

        // 2. 绑定资源处理器（返回静态JSON）
        return List.of(
                new McpServerFeatures.AsyncResourceSpecification(
                        resource,
                        (exchange, request) -> Mono.just(
                                new McpSchema.ReadResourceResult(List.of(
                                        new McpSchema.TextResourceContents(
                                                request.uri(),
                                                "application/json",
                                                "{\"os\":\"Linux\", \"memory\":\"8GB\"}" // 静态数据
                                        )
                                ))
                        )
                )
        );
    }

    @Bean
    public List<McpServerFeatures.SyncResourceSpecification> dynamicResources() {
        McpSchema.Resource resource = new McpSchema.Resource(
                "user-profile",
                "用户画像",
                "根据ID查询用户行为数据",
                "application/json",
                null
        );

        return List.of(
                new McpServerFeatures.SyncResourceSpecification(resource, (exchange, request) -> {
                    // 动态生成数据（示例：从数据库查询）
//                   String userId = request.arguments().get("userId"); // 从请求参数获取
//                   Map<String, Object> profile = userService.getProfile(userId);
                    //为了测试，直接返回一个静态数据
                    Map<String, Object> profile = new HashMap<>();
                    profile.put("name", "张三");
                    String json = null;
                    try {
                        json = new ObjectMapper().writeValueAsString(profile);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }

                    return new McpSchema.ReadResourceResult(List.of(
                            new McpSchema.TextResourceContents(request.uri(), "application/json", json)
                    ));
                })
        );
    }


    //提示词管理
    @Bean
    public List<McpServerFeatures.SyncPromptSpecification> myPrompts() {
        var prompt = new McpSchema.Prompt("greeting", "A friendly greeting prompt",
                List.of(new McpSchema.PromptArgument("name", "The name to greet", true)));

        var promptSpecification = new McpServerFeatures.SyncPromptSpecification(prompt, (exchange, getPromptRequest) -> {
            String nameArgument = (String) getPromptRequest.arguments().get("name");
            if (nameArgument == null) { nameArgument = "friend"; }
            var userMessage = new McpSchema.PromptMessage(McpSchema.Role.USER, new McpSchema.TextContent("Hello " + nameArgument + "! How can I assist you today?"));
            return new McpSchema.GetPromptResult("A personalized greeting message", List.of(userMessage));
        });

        return List.of(promptSpecification);
    }


//    @Bean
//    public List<McpServerFeatures.SyncCompletionSpecification> myCompletions() {
//        var completion = new McpServerFeatures.SyncCompletionSpecification(
//                "code-completion",
//                "Provides code completion suggestions",
//                (exchange, request) -> {
//                    // Implementation that returns completion suggestions
//                    return new McpSchema.CompletionResult(List.of(
//                            new McpSchema.Completion("suggestion1", "First suggestion"),
//                            new McpSchema.Completion("suggestion2", "Second suggestion")
//                    ));
//                }
//        );
//
//        return List.of(completion);
//    }
}
